import React, { useState, useEffect } from 'react';
import { listNetworks, createNetwork, deleteNetwork, startNetwork, stopNetwork } from '../api/client';
import './Networks.css';

interface Network {
  name: string;
  uuid: string;
  active: boolean;
  persistent: boolean;
  autostart: boolean;
  bridge: string;
  forwardMode: string;
  type: string;
}

interface NetworkFormData {
  name: string;
  forwardMode: string;
  bridge: string;
  ipAddress: string;
  netmask: string;
  dhcpStart: string;
  dhcpEnd: string;
  autostart: boolean;
}

const Networks: React.FC = () => {
  const [networks, setNetworks] = useState<Network[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [selectedNetworks, setSelectedNetworks] = useState<Set<string>>(new Set());
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [filterStatus, setFilterStatus] = useState<'all' | 'active' | 'inactive'>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [notification, setNotification] = useState<{ message: string; type: 'success' | 'error' | 'info' } | null>(null);

  const [formData, setFormData] = useState<NetworkFormData>({
    name: '',
    forwardMode: 'nat',
    bridge: '',
    ipAddress: '',
    netmask: '',
    dhcpStart: '',
    dhcpEnd: '',
    autostart: true
  });

  useEffect(() => {
    loadNetworks();
  }, []);

  const loadNetworks = async () => {
    try {
      setLoading(true);
      setError(null);

      console.log('Starting network load...');
      const response = await listNetworks();

      console.log('API Response:', response);
      console.log('Response data:', response.data);

      // Handle both direct array and wrapped response formats
      let networksArray = [];
      if (response.data && Array.isArray(response.data)) {
        networksArray = response.data;
      } else if (response.data && response.data.networks && Array.isArray(response.data.networks)) {
        networksArray = response.data.networks;
      } else if (response.data && response.data.networks === null) {
        networksArray = [];
      }

      console.log('Networks array:', networksArray);
      console.log('Networks array length:', networksArray.length);

      const networkData = networksArray.map((network: any) => ({
        name: network.name || network.Name || '',
        uuid: network.uuid || network.UUID || '',
        active: network.active !== undefined ? network.active : (network.Active || false),
        persistent: network.persistent !== undefined ? network.persistent : (network.Persistent || false),
        autostart: network.autostart !== undefined ? network.autostart : (network.Autostart || false),
        bridge: network.bridge || network.Bridge || '',
        forwardMode: network.forward_mode || network.ForwardMode || network.forwardMode || 'nat',
        type: network.type || network.Type || network.forward_mode || network.ForwardMode || 'nat'
      }));

      console.log('Processed network data:', networkData);
      console.log('Setting networks state to:', networkData.length, 'networks');
      setNetworks(networkData);

      // Debug: Check if state is being set
      setTimeout(() => {
        console.log('Networks state should now be set');
      }, 100);

    } catch (err) {
      console.error('Failed to load networks:', err);
      setError('Failed to load networks. Please make sure the API server is running.');
    } finally {
      setLoading(false);
    }
  };

  const showNotification = (message: string, type: 'success' | 'error' | 'info') => {
    setNotification({ message, type });
    setTimeout(() => setNotification(null), 3000);
  };

  const filteredNetworks = networks.filter(network => {
    const matchesSearch = network.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === 'all' || 
                         (filterStatus === 'active' && network.active) || 
                         (filterStatus === 'inactive' && !network.active);
    return matchesSearch && matchesStatus;
  });

  const handleCreateNetwork = async () => {
    if (!formData.name.trim()) {
      showNotification('Please enter a network name', 'error');
      return;
    }

    try {
      const networkData = {
        name: formData.name,
        forward_mode: formData.forwardMode,
        bridge: formData.bridge || undefined,
        ip_address: formData.ipAddress || undefined,
        netmask: formData.netmask || undefined,
        dhcp_start: formData.dhcpStart || undefined,
        dhcp_end: formData.dhcpEnd || undefined,
        autostart: formData.autostart,
        persistent: true
      };

      await createNetwork(networkData);
      showNotification(`Network "${formData.name}" created successfully`, 'success');

      setFormData({
        name: '',
        forwardMode: 'nat',
        bridge: '',
        ipAddress: '',
        netmask: '',
        dhcpStart: '',
        dhcpEnd: '',
        autostart: true
      });
      setShowCreateModal(false);
      loadNetworks();
    } catch (error) {
      console.error('Failed to create network:', error);
      showNotification('Failed to create network', 'error');
    }
  };

  const handleDeleteNetwork = async (networkName: string) => {
    if (!confirm(`Are you sure you want to delete network "${networkName}"? This action cannot be undone.`)) {
      return;
    }

    try {
      await deleteNetwork(networkName);
      showNotification(`Network "${networkName}" deleted successfully`, 'success');
      loadNetworks();
    } catch (error) {
      console.error('Failed to delete network:', error);
      showNotification('Failed to delete network', 'error');
    }
  };

  const handleBulkDelete = async () => {
    if (selectedNetworks.size === 0) {
      showNotification('Please select networks to delete', 'error');
      return;
    }

    if (!confirm(`Are you sure you want to delete ${selectedNetworks.size} network(s)? This action cannot be undone.`)) {
      return;
    }

    try {
      const promises = Array.from(selectedNetworks).map(name => deleteNetwork(name));
      await Promise.all(promises);
      showNotification(`${selectedNetworks.size} network(s) deleted successfully`, 'success');
      setSelectedNetworks(new Set());
      loadNetworks();
    } catch (error) {
      console.error('Failed to delete networks:', error);
      showNotification('Failed to delete some networks', 'error');
    }
  };

  const handleNetworkSelect = (networkName: string) => {
    const newSelected = new Set(selectedNetworks);
    if (newSelected.has(networkName)) {
      newSelected.delete(networkName);
    } else {
      newSelected.add(networkName);
    }
    setSelectedNetworks(newSelected);
  };

  const handleToggleNetwork = async (networkName: string, active: boolean) => {
    try {
      if (active) {
        await startNetwork(networkName);
        showNotification(`Network "${networkName}" started successfully`, 'success');
      } else {
        await stopNetwork(networkName);
        showNotification(`Network "${networkName}" stopped successfully`, 'success');
      }
      loadNetworks();
    } catch (error) {
      console.error('Failed to toggle network:', error);
      showNotification('Failed to toggle network', 'error');
    }
  };

  const renderNetworkCard = (network: Network) => {
    const isSelected = selectedNetworks.has(network.name);
    
    return (
      <div 
        className={`network-card ${viewMode} ${isSelected ? 'selected' : ''} ${network.active ? 'active' : 'inactive'}`}
        onClick={(e) => {
          if ((e.target as HTMLElement).closest('button')) return;
          handleNetworkSelect(network.name);
        }}
      >
        <div className="network-header">
          <div className="network-name">
            <input
              type="checkbox"
              checked={isSelected}
              onChange={() => handleNetworkSelect(network.name)}
              onClick={(e) => e.stopPropagation()}
            />
            <h3 title={network.name}>{network.name}</h3>
            <span className={`status-indicator ${network.active ? 'active' : 'inactive'}`}>
              {network.active ? '●' : '○'}
            </span>
          </div>
          <div className="network-actions">
            <button
              className={network.active ? 'stop' : 'start'}
              onClick={(e) => {
                e.stopPropagation();
                handleToggleNetwork(network.name, !network.active);
              }}
              title={network.active ? 'Stop network' : 'Start network'}
            >
              {network.active ? '⏹' : '▶'}
            </button>
            <button
              className="delete"
              onClick={(e) => {
                e.stopPropagation();
                handleDeleteNetwork(network.name);
              }}
              title="Delete network"
            >
              🗑
            </button>
          </div>
        </div>
        
        <div className="network-details">
          <div className="detail-item">
            <span className="detail-label">UUID:</span>
            <span className="detail-value" title={network.uuid}>{network.uuid.substring(0, 8)}...</span>
          </div>
          <div className="detail-item">
            <span className="detail-label">Type:</span>
            <span className="detail-value">{network.type}</span>
          </div>
          <div className="detail-item">
            <span className="detail-label">Bridge:</span>
            <span className="detail-value">{network.bridge || 'N/A'}</span>
          </div>
          <div className="detail-item">
            <span className="detail-label">Forward:</span>
            <span className="detail-value">{network.forwardMode}</span>
          </div>
          <div className="detail-item">
            <span className="detail-label">Persistent:</span>
            <span className="detail-value">{network.persistent ? 'Yes' : 'No'}</span>
          </div>
          <div className="detail-item">
            <span className="detail-label">Autostart:</span>
            <span className="detail-value">{network.autostart ? 'Yes' : 'No'}</span>
          </div>
        </div>
      </div>
    );
  };

  if (loading) {
    console.log('Rendering loading state...');
    return (
      <div className="networks-page">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>Loading networks...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="networks-page">
        <div className="error-card">
          <div className="error-icon">⚠️</div>
          <h3>Connection Error</h3>
          <p>{error}</p>
          <button onClick={loadNetworks} className="primary">
            Try Again
          </button>
        </div>
      </div>
    );
  }

  // console.log('Rendering Networks component...');
  // console.log('Current networks state:', networks);
  // console.log('Current loading state:', loading);
  // console.log('Current error state:', error);

  return (
    <div className="networks-page">
      {/* Notification System */}
      {notification && (
        <div className={`notification notification-${notification.type}`}>
          <span className="notification-icon">
            {notification.type === 'success' ? '✅' : notification.type === 'error' ? '❌' : 'ℹ️'}
          </span>
          <span className="notification-message">{notification.message}</span>
          <button
            className="notification-close"
            onClick={() => setNotification(null)}
          >
            ✕
          </button>
        </div>
      )}

      {/* Header */}
      <div className="page-header">
        <div className="header-content">
          <h1>Networks</h1>
          <div className="header-meta">
            <span className="network-count">{filteredNetworks.length} networks</span>
            <span className="active-count">{networks.filter(n => n.active).length} active</span>
            {selectedNetworks.size > 0 && (
              <span className="selection-count">{selectedNetworks.size} selected</span>
            )}
          </div>
        </div>
        <div className="header-actions">
          {/* Search */}
          <div className="search-group">
            <input
              type="text"
              className="search-input"
              placeholder="Search networks..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* Filter */}
          <div className="filter-group">
            <select
              className="filter-select"
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value as any)}
            >
              <option value="all">All Networks</option>
              <option value="active">Active Only</option>
              <option value="inactive">Inactive Only</option>
            </select>
          </div>

          {/* View Toggle */}
          <div className="view-toggle">
            <button
              className={`view-btn ${viewMode === 'grid' ? 'active' : ''}`}
              onClick={() => setViewMode('grid')}
              title="Grid View"
            >
              ⊞
            </button>
            <button
              className={`view-btn ${viewMode === 'list' ? 'active' : ''}`}
              onClick={() => setViewMode('list')}
              title="List View"
            >
              ☰
            </button>
          </div>

          {/* Bulk Actions */}
          {selectedNetworks.size > 0 && (
            <div className="bulk-group">
              <button
                className="danger"
                onClick={handleBulkDelete}
              >
                Delete Selected ({selectedNetworks.size})
              </button>
            </div>
          )}

          {/* Refresh */}
          <button
            onClick={loadNetworks}
            title="Refresh"
          >
            ↻
          </button>

          {/* Create Network */}
          <button
            className="primary"
            onClick={() => setShowCreateModal(true)}
          >
            + Create Network
          </button>
        </div>
      </div>

      {/* Bulk Selection Bar */}
      {selectedNetworks.size > 0 && (
        <div className="bulk-selection-bar">
          <div className="selection-info">
            <span className="selection-count">{selectedNetworks.size} network(s) selected</span>
          </div>
          <div className="bulk-actions">
            <button
              className="danger"
              onClick={handleBulkDelete}
            >
              Delete All Selected
            </button>
            <button
              className="secondary"
              onClick={() => setSelectedNetworks(new Set())}
            >
              Clear Selection
            </button>
          </div>
        </div>
      )}

      {/* Networks Grid/List */}
      {filteredNetworks.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🌐</div>
          <h3>No Networks Found</h3>
          <p>
            {searchTerm || filterStatus !== 'all'
              ? 'No networks match your search criteria.'
              : 'Create your first virtual network to get started.'}
          </p>
          {!searchTerm && filterStatus === 'all' && (
            <button
              className="primary"
              onClick={() => setShowCreateModal(true)}
            >
              Create Network
            </button>
          )}
        </div>
      ) : (
        <div className={`network-container ${viewMode}`}>
          {filteredNetworks.map((network) => renderNetworkCard(network))}
        </div>
      )}

      {/* Create Network Modal */}
      {showCreateModal && (
        <div className="modal-overlay" onClick={() => setShowCreateModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>Create Network</h2>
              <button
                className="modal-close"
                onClick={() => setShowCreateModal(false)}
              >
                ✕
              </button>
            </div>

            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">Network Name *</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  placeholder="Enter network name"
                  required
                />
              </div>

              <div className="form-group">
                <label className="form-label">Forward Mode</label>
                <select
                  className="form-select"
                  value={formData.forwardMode}
                  onChange={(e) => setFormData({...formData, forwardMode: e.target.value})}
                >
                  <option value="nat">NAT</option>
                  <option value="bridge">Bridge</option>
                  <option value="route">Route</option>
                  <option value="none">Isolated</option>
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">Bridge Name (Optional)</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.bridge}
                  onChange={(e) => setFormData({...formData, bridge: e.target.value})}
                  placeholder="virbr0"
                />
              </div>

              <div className="form-group">
                <label className="form-label">IP Configuration</label>
                <div className="ip-config-group">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.ipAddress}
                    onChange={(e) => setFormData({...formData, ipAddress: e.target.value})}
                    placeholder="IP Address (e.g., 192.168.100.1)"
                  />
                  <input
                    type="text"
                    className="form-input"
                    value={formData.netmask}
                    onChange={(e) => setFormData({...formData, netmask: e.target.value})}
                    placeholder="Netmask (e.g., 255.255.255.0)"
                  />
                </div>
              </div>

              <div className="form-group">
                <label className="form-label">DHCP Range (Optional)</label>
                <div className="dhcp-range-group">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.dhcpStart}
                    onChange={(e) => setFormData({...formData, dhcpStart: e.target.value})}
                    placeholder="Start IP"
                  />
                  <span className="range-separator">to</span>
                  <input
                    type="text"
                    className="form-input"
                    value={formData.dhcpEnd}
                    onChange={(e) => setFormData({...formData, dhcpEnd: e.target.value})}
                    placeholder="End IP"
                  />
                </div>
              </div>

              <div className="form-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={formData.autostart}
                    onChange={(e) => setFormData({...formData, autostart: e.target.checked})}
                  />
                  Enable autostart
                </label>
              </div>
            </div>

            <div className="modal-footer">
              <button
                className="secondary"
                onClick={() => setShowCreateModal(false)}
              >
                Cancel
              </button>
              <button
                className="primary"
                onClick={handleCreateNetwork}
                disabled={!formData.name.trim()}
              >
                Create Network
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Networks;